package flights.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import flights.bi.Flight_Seat;
import flights.db.FlightSeatHandler;

/**
 * Servlet implementation class FlightSeatServlet
 */
public class FlightSeatServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FlightSeatServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PrintWriter out = response.getWriter();
		String url = request.getPathInfo();
		response.setContentType( "text/html" ); 
		if (url != null && url.indexOf("get") != -1)
		{
			String fid = request.getParameter("fid");
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
			try
			{
				List<Flight_Seat> seats = FlightSeatHandler.getAllFlight_SeatsByFlight(Integer.parseInt(fid));
				out.print(gson.toJson(seats));
			}
			catch (Exception e)
			{
				out.print(e.getMessage());
			}
			
		}
		if (url != null && url.indexOf("remove") != -1)
		{
			String seatID = request.getParameter("sid");
			int nRows = 0;
			try {
				nRows = FlightSeatHandler.deleteFlight_SeatByID(Integer.parseInt(seatID));
			} catch (NumberFormatException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			out.write("{\"rows\":" + nRows + "}");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String url = request.getPathInfo();
		response.setContentType("text/html"); 
		if (url != null && url.indexOf("update") != -1)
		{
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
			String flightJson = request.getParameter("seat");
			if (flightJson != null && !flightJson.isEmpty()) {
				
				Type seatType = new TypeToken<Flight_Seat>(){}.getType();
				Flight_Seat seat = gson.fromJson(flightJson, seatType);
				
				int nRows;
				try {
					nRows = FlightSeatHandler.upsertFlight_Seat(seat);
					out.write("{rows:" + nRows + "}");
				} catch (SQLException e) {
					out.write(e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}

}
